package com.iamteer.servlet;
/**
 * 4. 控制层开发
 */
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamteer.entity.Employee;
import com.iamteer.service.IEmployeeService;
import com.iamteer.service.impl.EmployeeService;
import com.iamteer.utils.PageBean;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	// 创建 Service 实例
	private IEmployeeService employeeService = new EmployeeService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 1. 获取当前页参数（第一次访问为 null）
			String currPage = request.getParameter("currentPage");
			// 判断
			if (currPage == null || "".equals(currPage.trim())) {
				currPage = "1";	//第一次访问，设置当前页为 1；
			}
			// 转换
			int currentPage = Integer.parseInt(currPage);
			
			// 2. 创建 PageBean 对象，设置当前页参数，传入 service 方法参数
			PageBean<Employee> pageBean = new PageBean<Employee>();
			pageBean.setCurrentPage(currentPage);
			
			// 3. 调用 service
			employeeService.getAll(pageBean);	//[pageBean 已经被填充了数据]
			
			// 4. 保存 pageBean 对象到 request 域中
			request.setAttribute("pageBean", pageBean);
			
			// 5. 跳转
			request.getRequestDispatcher("/WEB-INF/list.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();	// 测试使用
			// 出现错误，跳转到错误页面，给用户友好提示
			request.getRequestDispatcher("/error/error.jsp").forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
